const WebSocket = require('ws');
const fs = require('fs')
const path = require('path')
const mainPath = path.join(__dirname, './dist/')
const soundsjPath = path.join(mainPath, '/main.json')
var sounds = [];
var i = 1;

// 生成16位数据
function message(str) {
    var len = str.length;
    var buffer = new ArrayBuffer(len + 12);
    new DataView(buffer).setInt16(0, len + 8, true);
    new DataView(buffer).setInt16(4, len + 8, true);
    new DataView(buffer).setInt16(8, 45314, false);
    var bufView = new Uint8Array(buffer, 12);
    for (var i = 0; i < len; i++) {
        bufView[i] = str.charCodeAt(i);
    }
    return buffer;
}


// 连接Websocket
var ws = new WebSocket('wss://danmuproxy.douyu.com:8506/');

ws.on('open', function open() {
    var str = 'type@=loginreq/roomid@=762505/dfl@=/username@=visitor8243989/uid@=1132317461/ver@=20230722/aver@=218101901/ct@=0/' + '\0';
    var buffer = message(str);
    ws.send(buffer);
    var str1 = "type@=joingroup/rid@=762505/gid@=-9999/" + "\0";
    var buffer1 = message(str1);
    setTimeout(() => {
        ws.send(buffer1);
    }, 1000);
    setInterval(() => {
        ws.send(message("type@=mrkl/" + '\0'));
    }, 45000);
});

ws.onmessage = function (event) {
    const receivedMessage = event.data;

    var m = receivedMessage.toString()

    // 用户
    function getName(data) {
        let strUrl = data;
        let pattern = /(\/nn@=)/
        if (pattern.test(strUrl)) {
            let arrUrl = strUrl.split("/nn@=");
            let strPage = arrUrl[arrUrl.length - 1];
            if (strPage.indexOf("/") > -1) {
                let pageName = strPage.split("/");
                strPage = pageName[0];
            }
            return strPage;
        } else {
            return "";
        }
    }

    // 内容
    function getText(data) {
        let strUrl = data;
        let pattern = /(\/txt@=)/
        if (pattern.test(strUrl)) {
            let arrUrl = strUrl.split("/txt@=");
            let strPage = arrUrl[arrUrl.length - 1];
            if (strPage.indexOf("/") > -1) {
                let pageName = strPage.split("/");
                strPage = pageName[0];
            }
            return strPage;
        } else {
            return ""
        }
    }


    // 输出格式化的内容
    var TextS;
    if (getName(m) != "" & getText(m) == "") {
        TextS = getName(m) + "：" + "欢迎来到本直播间"
        console.log(TextS);
    }
    if (getName(m) != "" & getText(m) != "") {
        TextS = getName(m) + "：" + getText(m)
        if (sounds[i] != "") {
            sounds[i] = sounds[i] || {};
            sounds[i] = {
                name: getName(m),
                text: getText(m)
            }
        }
        sounds = sounds.filter(item => item != null);
        console.log(TextS);

        if (fs.existsSync(mainPath)) {
            const jsonData = JSON.stringify(sounds);
            fs.writeFile(soundsjPath, jsonData, 'utf-8', (err) => {
                if (err) {
                    console.log(err);
                }
            });
        } else {
            console.log("error");
        }
    }

    i++

};
